package com.cw.interceptor;

import com.cw.utils.JwtUtils;
import com.cw.utils.R;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @program: MySyetem
 * @description: 登录拦截
 * @author: 张庆恒
 * @create: 2021-08-28 18:42
 **/
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        System.out.println(method);
        if ("OPTIONS".equalsIgnoreCase(method)) {
            return true;
        }
        String path = request.getServletPath();
        System.out.println(path);
        if ("/login".equals(path)) {
            return true;
        }
        //获取请求头中的token
        String token = request.getHeader("token");
        if (token != null) {
            try {
                JwtUtils.verifyToken(token);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        R r = new R(0, "请先登录", 0, null);
        writer.print(r.getMsg());
        writer.flush();
        writer.close();
        return false;
    }
}
